package com.lingshu.app.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.lingshu.app.config.App;
import com.lingshu.app.database.bean.MessageBean;
import com.lingshu.app.network.CustomDisposable;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Completable;
import io.reactivex.Flowable;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/15 13:43
 * @Description
 */
public class MessageRepository extends BaseRepository<MessageBean> {
    private static final String TAG = MessageRepository.class.getSimpleName();

    @Inject
    MessageRepository() {

    }

    public void saveMessages(MessageBean... messageBeans) {
        Completable completable = App.getDb().getMessageDao().insert(messageBeans);
        CustomDisposable.addDisposable(completable, () -> {
            Log.d(TAG, "saveMessages: 数据保存成功");
        });
    }

    public void updateMessages(MessageBean... messageBeans) {
        Completable completable = App.getDb().getMessageDao().update(messageBeans);
        CustomDisposable.addDisposable(completable, () -> {
            Log.d(TAG, "updateMessages: 数据更新成功");
        });
    }

    public MutableLiveData<MessageBean> getMessage(int id) {
        Flowable<MessageBean> flowable = App.getDb().getMessageDao().get(id);
        CustomDisposable.addDisposable(flowable, messageBean -> {
            if (messageBean != null) {
                dataDetail.postValue(messageBean);
            }
        });
        return dataDetail;
    }

    public MutableLiveData<Integer> getCount() {
        CustomDisposable.addDisposable(App.getDb().getMessageDao().getCount(), result -> {
            totalCount.postValue(result);
        });
        return totalCount;
    }

    public MutableLiveData<List<MessageBean>> getPagedList(int pageSize, int offset) {
        CustomDisposable.addDisposable(App.getDb().getMessageDao().getPagedList(pageSize, offset), messageBeans -> {
            if (messageBeans.size() > 0) {
                dataList.postValue(messageBeans);
            } else {
                dataList.postValue(emptyList);
            }
        });
        return dataList;
    }
}
